<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公告标题" prop="noticeTitle">
        <el-input
          v-model="queryParams.noticeTitle"
          placeholder="请输入公告标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="公告类型" prop="noticeType">
        <el-select v-model="queryParams.noticeType" placeholder="请选择公告类型" clearable>
          <el-option
            v-for="dict in sys_notice_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="公告状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择公告状态" clearable>
          <el-option
            v-for="dict in sys_notice_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="人员选择">
        <el-input placeholder="请选择人员" class="selectUser" clearable v-model="choiceUserNames" @click="iframeShow" @clear="clearSelectUser" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:notice:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:notice:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:notice:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['system:notice:add']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:notice:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="noticeList" @selection-change="handleSelectionChange" @sort-change="handleSortChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="公告ID" align="center" prop="noticeId" />
      <el-table-column label="公告标题" align="center" prop="noticeTitle" />
      <el-table-column label="公告类型" align="center" prop="noticeType"  sortable="custom" :sort-orders="['descending', 'ascending']" >
        <template #default="scope">
          <dict-tag :options="sys_notice_type" :value="scope.row.noticeType"/>
        </template>
      </el-table-column>
      <el-table-column label="公告内容" align="center" prop="noticeContent" />
      <el-table-column label="公告状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_notice_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy" width="100"/>
      <el-table-column label="创建时间" align="center" prop="createTime" sortable="custom" :sort-orders="['descending', 'ascending']"  width="100">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:notice:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:notice:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改通知公告new对话框 -->
    <el-dialog :title="title" v-model="open" width="850px" append-to-body>
      <el-form ref="noticeRef" :model="form" :inline="true" :rules="rules" label-width="80px">
        <el-form-item label="公告标题" prop="noticeTitle">
          <el-input v-model="form.noticeTitle" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item label="公告类型" prop="noticeType">
          <el-select v-model="form.noticeType" placeholder="请选择公告类型">
            <el-option
              v-for="dict in sys_notice_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="公告状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_notice_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="公告内容">
          <editor v-model="form.noticeContent" :min-height="192"/>
        </el-form-item>


        <el-divider content-position="center">公告评论信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddSysNoticeComment">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteSysNoticeComment">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="sysNoticeCommentList" :row-class-name="rowSysNoticeCommentIndex" @selection-change="handleSysNoticeCommentSelectionChange" ref="sysNoticeComment">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="评论" prop="comment" >
            <template #default="scope">
              <el-input v-model="scope.row.comment" placeholder="请输入评论" />
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" >
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 公告导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的公告数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--人员选择-->
    <el-dialog title="人员选择" class="userSelect" destroy-on-close v-model="userDialog" width="850px" height="400px" append-to-body>
      <user-select :selectType="selectListType" :selectConfig="iframeConfig" @getSelectUserInfo="saveSelectUser"></user-select>
    </el-dialog>
  </div>
</template>

<script setup>
import { listNotice, getNotice, delNotice, addNotice, updateNotice } from "@/api/system/notice";
import {getToken} from "@/utils/auth";
import Conf from '@/utils/conf'
import  UserSelect  from "@/components/UserSelect";
const { proxy } = getCurrentInstance();
const { sys_notice_status, sys_notice_type } = proxy.useDict('sys_notice_status', 'sys_notice_type');

const noticeList = ref([]);
const sysNoticeCommentList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedSysNoticeComment = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: Conf.VITE_APP_BASE_API + "/system/notice/importData"
});
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    noticeTitle: null,
    noticeType: null,
    noticeContent: null,
    status: null,
    orderByColumn: null,
    isAsc: null
  },
  rules: {
    noticeTitle: [{ required: true, message: "公告标题不能为空", trigger: "blur" }],
    noticeType: [{ required: true, message: "公告类型不能为空", trigger: "change" }],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询通知公告new列表 */
async function getList() {
  loading.value = true;
  const response  = await listNotice(queryParams.value);
  noticeList.value = response.rows;
  total.value = response.total;
  loading.value = false;
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    noticeId: null,
    noticeTitle: null,
    noticeType: null,
    noticeContent: null,
    status: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  sysNoticeCommentList.value = [];
  proxy.resetForm("noticeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.noticeId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加通知公告new";
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  const _noticeId = row.noticeId || ids.value;
  const response = await getNotice(_noticeId);
  form.value = response.data;
  sysNoticeCommentList.value = response.data.sysNoticeCommentList;
  open.value = true;
  title.value = "修改通知公告new";
}

/** 提交按钮 */
async function submitForm() {
  try {
    const valid = await proxy.$refs["noticeRef"].validate();
    if (valid) {
      form.value.sysNoticeCommentList = sysNoticeCommentList.value;
      if (form.value.noticeId != null) {
        await updateNotice(form.value);
        proxy.$modal.msgSuccess("修改成功");
      } else {
        await addNotice(form.value);
        proxy.$modal.msgSuccess("新增成功");
      }
      open.value = false;
      getList();
    }
  } catch (error) {
    // 校验失败界面自动有红色标记，可以不需要提示； 接口调用失败有接口本身的错误提示
  }
}

/** 删除按钮操作 */
async function handleDelete(row) {
  try {
    const _noticeIds = row.noticeId || ids.value;
    await proxy.$modal.confirm('是否确认删除通知公告new编号为"' + _noticeIds + '"的数据项？');
    await delNotice(_noticeIds);
    getList();
    proxy.$modal.msgSuccess("删除成功");
  } catch (error) {
    // 用户取消会走到这里，不需要提示； 接口调用失败有接口本身的错误提示
  }
}

/** 公告评论序号 */
function rowSysNoticeCommentIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 公告评论添加按钮操作 */
function handleAddSysNoticeComment() {
  const obj = {};
  obj.comment = "";
  obj.remark = "";
  sysNoticeCommentList.value.push(obj);
}

/** 公告评论删除按钮操作 */
function handleDeleteSysNoticeComment() {
  if (checkedSysNoticeComment.value.length === 0) {
    proxy.$modal.msgError("请先选择要删除的公告评论数据");
  } else {
    const sysNoticeComments = sysNoticeCommentList.value;
    const checkedSysNoticeComments = checkedSysNoticeComment.value;
    sysNoticeCommentList.value = sysNoticeComments.filter(function(item) {
      return checkedSysNoticeComments.indexOf(item.index) === -1
    });
  }
}

/** 复选框选中数据 */
function handleSysNoticeCommentSelectionChange(selection) {
  checkedSysNoticeComment.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('/system/notice/export', {
    ...queryParams.value
  }, `notice_${new Date().getTime()}.xlsx`)
}

/** 排序触发事件 */
function handleSortChange(column, prop, order) {
  queryParams.value.orderByColumn = column.prop;
  queryParams.value.isAsc = column.order;
  getList();
}
/** 导入按钮操作 */
function handleImport() {
  upload.title = "通知公告导入";
  upload.open = true;
}
/** 下载模板操作 */
function importTemplate() {
  proxy.download("/system/notice/importTemplate", {
  }, `通知公告 模版_${new Date().getTime()}.xlsx`);
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
}
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}
getList();

/**
 * 人员弹窗
 */
// 人员弹窗显示状态
const userDialog = ref(false);
// 弹窗列表部门类型
const selectListType = ref("p");
// 选中的人员名称
const choiceUserNames = ref("");
// 选中的人员ID
const choiceUserIds = ref("");
// iframe参数
const iframeConfig = ref({})

// 选择人员弹窗事件
const iframeShow = () => {
  userDialog.value = true;
};

// 清除选中人员信息
const clearSelectUser = () => {
  choiceUserNames.value = "";
  choiceUserIds.value = "";
};

// 存储选择人员信息
const saveSelectUser = (userObj) => {
  [choiceUserIds.value, choiceUserNames.value] = userObj;
  // 关闭弹窗
  userDialog.value = false;
}

// 挂载后执行
onMounted(() => {
  iframeConfig.value = {
    userSelectIframeUrl: Conf.VITE_IFRAME_SELECT_USER,
    cookieDomain: Conf.VITE_COOKIE_DOMAIN,
    postMessageTargetOrigin: Conf.VITE_POSTMESSAGE_TARGET_ORIGIN
  }
});
</script>
<style lang='scss' scoped>
.selectUser{
  width: 200px;
}
</style>
